package service4admin

import (
	"Gin-Gorm-boke/boke_common/models"
	"Gin-Gorm-boke/boke_common/response"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"strconv"
)

func CategoryPageList(c *gin.Context) {
	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	name := c.Query("name")
	status := c.Query("status")
	db := models.Db.Model(new(models.CategoryVo))
	if name != "" {
		db.Where("name like ?", "%"+name+"%")
	}
	if status != "" {
		db.Where("status = ?", status)
	}
	var total int64
	db.Count(&total)
	var categoryList []models.CategoryVo
	db.Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&categoryList)
	response.ResponseOK(c, gin.H{
		"total": total,
		"rows":  categoryList,
	})
	return
}

func SaveCategory(c *gin.Context) {
	var categoryDto models.CategoryDto
	var category models.Category
	if err := c.ShouldBindJSON(&categoryDto); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	copier.Copy(&category, &categoryDto)
	category.Status = strconv.Itoa(int(categoryDto.Status.Int64))

	models.Db.Create(&category)
	response.ResponseOK(c, nil)
	return
}

func UpdateCategory(c *gin.Context) {
	var categoryDto models.CategoryDto
	var category models.Category
	if err := c.ShouldBindJSON(&categoryDto); err != nil {
		response.ResponseBadRequest(c)
		return
	}
	copier.Copy(&category, &categoryDto)
	category.Status = strconv.Itoa(int(categoryDto.Status.Int64))
	models.Db.Model(new(models.Category)).Where("id=?", category.Id).Updates(&category)
	response.ResponseOK(c, nil)
	return
}

func GetCategoryById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	var category models.CategoryVo
	models.Db.Where("id=?", id).Find(&category)
	response.ResponseOK(c, category)
	return
}

func DelCategory(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	models.Db.Model(new(models.Category)).Where("id=?", id).Update("del_flag", "1")
	models.Db.Where("id=?", id).Delete(&models.Category{})
	response.ResponseOK(c, nil)
	return

}
